<template>
  <div>
    <el-select v-if="!disabled" v-model="val" clearable filterable placeholder="请选择" size="mini" :style="{width: width + 'px'}" @change="onChange">
      <el-option v-for="item in options" :key="item.code" :label="item.name" :value="item.code" />
    </el-select>
    <span v-else>{{ name }}</span>
  </div>
</template>

<script>
import store from './store'
export default {
  name: 'ForeignSelect',
  props: {
    schema: {
      type: [String, Number],
      default: ''
    },
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    width: {
      type: Number,
      default: 100
    }
  },
  data() {
    return {
      val: this.value,
      options: []
    }
  },
  computed: {
    name() {
      const option = this.options.find(it => it.code === this.val)
      if (option) {
        return option.name
      } else {
        return this.val
      }
    }
  },
  watch: {
    schema(newVal, oldVal) {
      this.fetch(newVal)
    }
  },
  created() {
    if (this.schema !== '') {
      this.fetch(this.schema)
    }
  },
  methods: {
    onChange() {
      this.$emit('input', this.val)
    },
    fetch(schema) {
      store.fetch(schema).then(response => {
        this.options = response.data
      })
    }
  }
}
</script>
